import configparser
import paho.mqtt.client as mqtt
import os


mqtt_server = 'aahqtdc.iot.gz.baidubce.com'
client_id = None
mqtt_username=None
mqtt_password = None
mqtt_port = 1883
mqtt_keep_alive = 120
client = None
target = None
on_message_callback = None

def read_config(f_name:str):
    global mqtt_server, client_id, mqtt_username, mqtt_password, mqtt_port, mqtt_keep_alive, target
    config = configparser.ConfigParser()
    config.read(f_name)
    mqtt_server = config.get('mqtt', 'server', fallback=mqtt_server)
    client_id = config.get('mqtt', 'client_id')
    assert client_id
    mqtt_username = f'thingidp@aahqtdc|{client_id}'
    mqtt_password = config.get('mqtt', 'password')
    assert mqtt_password
    mqtt_port = config.getint('mqtt', 'port', fallback=mqtt_port)
    mqtt_keep_alive = config.getint('mqtt', 'keep_alive', fallback=mqtt_keep_alive)
    target = config.get('mqtt', 'target')
    if 'jc-target' in os.environ:
        target = os.environ['JCTarget']
    
    assert target


def on_connect(client, userdata, flags, rc):
    if rc:
        raise Exception('connect failed')
    print('connected')
    

def on_disconnect(client, userdata, flags):
    raise Exception('disconnected')

def client_publish(topic, data):
    client.publish(f'lily/{target}/{topic}', data)

def mqtt_out(msg: str, end='\n'):
    client.publish(f'lily/{target}/cmd', msg+end)


def mqtt_out_raw(msg: bytes):
    client.publish(f'lily/{target}/cmd', msg)


def on_message(client_name, userdata, msg):
    topic = msg.topic
    if on_message_callback:
        on_message_callback(msg.payload, topic)


def set_on_message(f):
    global on_message_callback
    on_message_callback = f

def start_loop():
    global client
    client = mqtt.Client(client_id)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_message = on_message
    client.on_connect_fail = lambda a, b, c: exit(-1)
    client.username_pw_set(mqtt_username, mqtt_password)
    client.connect(mqtt_server, mqtt_port, mqtt_keep_alive)
    client.subscribe(f'lily/{target}/msg')
    client.subscribe(f'lily/{target}/pong')
    client.loop_start()

def stop_loop():
    global client
    client.loop_stop()
    try:
        client.disconnect()
    except:
        pass

if __name__ == '__main__':
    import sys
    import os
    start_loop()
    columns, lines = os.get_terminal_size()
    print(f'rows {lines} cols {columns}')
    mqtt_out(f'pty -r')
    mqtt_out(f'stty rows {lines} cols {columns}')
    mqtt_out(f'export TERM=xterm-256color')
    on_message_callback = lambda s: print(s.decode('utf-8'), end='')
    client.loop_start()
    try:
        while 1:
            msg = input()
            mqtt_out(msg)
    except:
        stop_loop()
        exit(0)
    